package com.sita.friend.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.OnDismissListener;
import com.sita.bike.R;
import com.sita.bike.model.EaseUser2;
import com.sita.bike.persistence.TrendMember;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Audio;
import com.sita.bike.rest.model.Picture;
import com.sita.bike.rest.model.RtResource;
import com.sita.bike.rest.model.request.RtDelResourceRequest;
import com.sita.bike.rest.model.response.RtDelResourceResponse;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.friend.FriendHelper;
import com.sita.tboard.ui.activity.ImagePagerActivity;
import com.sita.tboard.ui.adapter.TrendsGridAdapter;
import com.sita.tboard.ui.tools.AudioPlayer;
import com.sita.tboard.ui.tools.L;
import com.sita.tboard.util.DateUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class RtFriendResAdapter extends RecyclerView.Adapter<RtFriendResAdapter.ViewHolder> {

    private ArrayList<RtResource> mData;

    private AudioPlayer mPlayer;
    private AnimationDrawable mAnimationDrawable;

    private Context context;

    public RtFriendResAdapter(ArrayList<RtResource> mData, AudioPlayer audioPlayer) {
        this.mData = mData;
        mPlayer = audioPlayer;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();

        View view = LayoutInflater.from(context).inflate(R.layout.friend_res_item, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        String avatar = "";
        String nick = "";
        String title = "";

        final RtResource res = mData.get(position);
        final List<Picture> pics = res.pics;
        final List<Audio> audios = res.audios;
        String time = DateUtils.translateDateTime(res.createDate);
        holder.time.setText(time);

        if (res.accountId.equals(AccountUtils.getAccountID())) {
            // 本人
            avatar = AccountUtils.getAvatar();
            nick = AccountUtils.getNickName();
        } else {
            // 好友
            EaseUser2 friend = FriendHelper.getInstance().getContactUser(res.accountId);
            if (friend != null) {
                avatar = friend.getAvatarUrl();
                nick = friend.getUsername().equals("") ? friend.getNick() : friend.getUsername();
            } else {
                // 非好友
                TrendMember member = PersistUtils.getTrendMember(res.accountId);
                if (member != null) {
                    avatar = member.getAvatarUrl();
                    nick = member.getNickname();
                }
            }
        }
        title = res.title;
        if (!android.text.TextUtils.isEmpty(avatar)) {
            Picasso.with(GlobalContext.getGlobalContext()).load(avatar).fit()
                    .into(holder.avatar);
        }
        holder.content.setText(title);
        holder.nickname.setText(nick);

        mAnimationDrawable = (AnimationDrawable) context.getResources().getDrawable(R.drawable.animation);
        holder.voice.setImageResource(R.drawable.wifi);
        if (audios != null && !audios.isEmpty()) {
            holder.voice.setVisibility(View.VISIBLE);
            holder.voice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mPlayer.isPlaying()) {
                        mPlayer.stop();
                        mAnimationDrawable.stop();
                        holder.voice.setImageResource(R.drawable.wifi);
                    } else {
                        mPlayer.setMCompletion(new AudioPlayer.MCompletion() {
                            @Override
                            public void Complete() {
                                mAnimationDrawable.stop();
                                holder.voice.setImageResource(R.drawable.wifi);
                            }
                        });
                        holder.voice.setImageDrawable(mAnimationDrawable);
                        mPlayer.play(context, audios.get(0).mUrl);
                        mAnimationDrawable.start();
                    }
                }
            });
        } else {
            holder.voice.setVisibility(View.GONE);
            if (mAnimationDrawable != null) {
                mAnimationDrawable.stop();
            }
        }
        if (pics != null && !pics.isEmpty()) {
            holder.gallery.setVisibility(View.VISIBLE);
            final ArrayList<String> links = new ArrayList<String>();
            for (Picture dpp : pics) {
                links.add(dpp.mUrl);
            }
            holder.gallery.setAdapter(new TrendsGridAdapter(links, context));
            holder.gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    imageBrowser(position, links);
                }
            });
        } else {
            holder.gallery.setVisibility(View.GONE);
        }

        holder.action.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openChooseMenu(res);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void appendTop(RtResource res) {
        insert(res, 0);
        notifyItemChanged(0);
    }

    public void append(RtResource res) {
        int pos = mData.size();
        insert(res, pos);
        notifyItemChanged(pos);
    }

    private void insert(RtResource res, int position) {
        if (!mData.contains(res)) {
            mData.add(position, res);
            notifyItemInserted(position);
        }
    }

    public void clear() {
        mData.clear();
        notifyDataSetChanged();
    }

    private void openChooseMenu(final RtResource res){
        com.orhanobut.dialogplus.ViewHolder holder = new com.orhanobut.dialogplus.ViewHolder(
                R.layout.pop_menu_delete);

        final DialogPlus dialog = DialogPlus.newDialog(context)
                .setContentHolder(holder)
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(DialogPlus dialog, View view) {
                        if (view.getId() == R.id.act_delete) {
                            doDelete(res);
                            dialog.dismiss();
                        } else if (view.getId() == R.id.act_delete) {
                            dialog.dismiss();
                        }
                    }
                })
                .setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogPlus dialog) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(true)
                .create();
        dialog.show();
    }

    private void doDelete(final RtResource res){
        RtDelResourceRequest req = new RtDelResourceRequest(AccountUtils.getAccountID(), res.id);
        RestClient.getRestNormalService().rtDeleteResource(req, new Callback<RtDelResourceResponse>() {
            @Override
            public void success(RtDelResourceResponse delResp, Response response) {
                if (response.getStatus() == 200){
                    if (delResp.errorCode.equals("0")){
                        mData.remove(res);
                        notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                L.e("doDelete()", error);
            }
        });
    }

    private void imageBrowser(int position, ArrayList<String> links) {
        Intent intent = new Intent(context, ImagePagerActivity.class);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, links);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        context.startActivity(intent);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.avatar)
        CircleImageView avatar;
        @Bind(R.id.nickname)
        TextView nickname;
        @Bind(R.id.item_voice)
        ImageView voice;
        @Bind(R.id.item_time)
        TextView time;
        @Bind(R.id.item_content)
        TextView content;
        @Bind(R.id.item_gallery)
        GridView gallery;
        @Bind(R.id.item_more)
        ImageView action;

        public ViewHolder(View itemView) {
            super(itemView);

            ButterKnife.bind(this, itemView);
        }
    }
}
